package com.socket.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.socket.core.constant.ChatProperties;
import com.socket.core.enums.RedisTree;
import com.socket.core.util.RedisClient;
import com.socket.server.mapper.ShieldUserMapper;
import com.socket.server.model.po.ShieldUser;
import com.socket.server.service.ShieldUserService;
import com.socket.server.util.ShiroUser;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.support.collections.RedisList;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ShieldUserServiceImpl extends ServiceImpl<ShieldUserMapper, ShieldUser> implements ShieldUserService {
    private final RedisClient<String> client;
    private final ChatProperties properties;

    public boolean shieldTarget(String target) {
        String guid = ShiroUser.getUserId();
        List<String> shields = getShieldList(guid);
        LambdaUpdateWrapper<ShieldUser> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(ShieldUser::getGuid, guid);
        wrapper.eq(ShieldUser::getTarget, target);
        // 包含此目标uid，取消屏蔽
        if (shields.contains(target)) {
            wrapper.set(ShieldUser::isDeleted, 1);
            super.update(wrapper);
            shields.remove(target);
            return false;
        }
        //  添加屏蔽
        ShieldUser suser = new ShieldUser();
        suser.setGuid(guid);
        suser.setTarget(target);
        super.save(suser);
        shields.add(target);
        return true;
    }

    @Override
    public List<String> getShieldList(String userId) {
        RedisList<String> redisList = client.withList(RedisTree.SHIELD, userId);
        // 检查缓存
        if (redisList.isEmpty()) {
            // 查询数据库
            LambdaQueryWrapper<ShieldUser> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(ShieldUser::getGuid, ShiroUser.getUserId());
            List<ShieldUser> users = list(wrapper);
            List<String> collect = users.stream().map(ShieldUser::getTarget).collect(Collectors.toList());
            redisList.addAll(collect);
            redisList.expire(properties.getShieldCacheTime(), TimeUnit.HOURS);
        }
        return redisList;
    }
}
